package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.business.mapper.ProductActiveMapper;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.purchase.domain.PurchaseOrder;
import com.dhecp.project.purchase.domain.PurchasePlan;
import com.dhecp.project.purchase.mapper.PurchaseOrderMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanMapper;
import com.dhecp.project.storage.domain.*;
import com.dhecp.project.storage.mapper.*;
import com.dhecp.project.storage.service.ProductAssembleService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: kjecp
 * @description: 仓储 组装单
 * @author: hlf
 * @create: 2022-09-01 14:27
 */
@Service
public class ProductAssembleServiceImpl extends BaseModuleServiceImpl implements ProductAssembleService {


    @Autowired
    private ProductAssembleMapper assembleMapper;

    @Autowired
    private PutawayMapper putawayMapper;
    @Autowired
    private PurchasingErrorMapper purchasingErrorMapper;
    @Autowired
    private ProductActiveMapper productActiveMapper;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;

    @Autowired
    private PurchasePlanMapper purchasePlanMapper;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private OtherCostMapper otherCostMapper;
    @Autowired
    private StockControlMapper stockControlMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.ProductAssemble>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<ProductAssemble> listByBid(String bid) {
        return assembleMapper.listByBid(bid);
    }

    /**
     * 通过组装单号查询组装单列表
     */
    @Override
    public ProductAssemble queryByGuid(String guid) {
        return assembleMapper.findByGuid(guid);
    }

    /**
     * 通过组装单号查询第一条数据
     */
    @Override
    public ProductAssemble queryFirstByBid(String bid) {
    	List<ProductAssemble> list = assembleMapper.listByBid(bid);
    	if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
    }

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = assembleMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = assembleMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.ProductAssemble
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public ProductAssemble queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return assembleMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.ProductAssemble>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<ProductAssemble> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return assembleMapper.selectByNid(params);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.ProductAssemble>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<ProductAssemble> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return assembleMapper.select(params);
    }

    /**
     * @Description: 查询整单
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.ProductAssemble>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<ProductAssemble> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return assembleMapper.selectgroup(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        ProductAssemble infoMap = JSON.parseObject(params.get("infoMap").toString(), ProductAssemble.class);
        List<ProductAssemble> productAssembles = JSON.parseArray(params.get("infoItems").toString(), ProductAssemble.class);

        List<Putaway> putaways = new ArrayList<>();
        putaways = putawayMapper.findByAssID(infoMap.getBid());

        for (ProductAssemble item : productAssembles
        ) {
            List<ProductActiveComponent> productActiveComponent = new ArrayList<>();

            productActiveComponent = productActiveMapper.queryProductActiveComponentByCode(item.getSonCode());

            item.setPlanNum(infoMap.getPlanNum());
            item.setActualNum(infoMap.getActualNum());
            item.setAuditor(ShiroUtils.getUserId());
            item.setaWay(infoMap.getaWay());
            item.setaName(infoMap.getaName());
            item.setHeight(infoMap.getHeight());
            item.setWeight(infoMap.getWeight());
            item.setWidth(infoMap.getWidth());
            item.setLength(infoMap.getLength());
            item.setSonUseTotal( (int) Math.round(productActiveComponent.get(0).getNum() * infoMap.getActualNum()));
//            item.setSonUseTotal((int) (productActiveComponent.get(0).getNum() * infoMap.getActualNum()));
            item.setEffectStock(true);
            item.setUpdateTime(new Date());
            item.setvZdbz(infoMap.getvZdbz());
            assembleMapper.update(item);
        }

        if (putaways.size() == 0) {
            Map<String, Object> paramsNid = new HashMap<>();
            paramsNid.put("nid", infoMap.getNid());
            List<ProductAssemble> productAssembles1 = assembleMapper.selectByNid(paramsNid);
            //生成 质检上架单
            getPutawayData(productAssembles1);
            //生成 采购报错单
//            getPurchasingErrorData(productAssembles1);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), infoMap.getNid());
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<ProductAssemble> businessDataList = JSON.parseArray(params.get("infoItems").toString(), ProductAssemble.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (ProductAssemble businessData : businessDataList) {
            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("nid", businessData.getNid());
            List<ProductAssemble> list = assembleMapper.selectByNid(params2);
            for (ProductAssemble item : list
            ) {
                assembleMapper.delete(item);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            assembleMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<ProductAssemble> businessDataList = assembleMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (ProductAssemble businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            assembleMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<ProductAssemble> businessDataList = assembleMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (ProductAssemble businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            assembleMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    /**
     * 修改审核状态
     *
     * @param params
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateType(Map<String, Object> params) {
        List<ProductAssemble> productAssembles = JSON.parseArray(params.get("infoItems").toString(), ProductAssemble.class);
        for (ProductAssemble item : productAssembles
        ) {
            if (item.getNid() != null) {
                List<Putaway> putaway = new ArrayList<>();
                putaway = putawayMapper.findByAssID(item.getBid());
                if (putaway.size()>0){
                    return AjaxResult.error("请先删除质检上架单!");
                }
                Map<String, Object> paramsNid = new HashMap<>();
                paramsNid.put("nid", item.getNid());
                List<ProductAssemble> productAssembles1 = assembleMapper.selectByNid(paramsNid);
                for (ProductAssemble item2 : productAssembles1
                ) {
                    if (item.getEffectStock()) {
                        item2.setEffectStock(item.getEffectStock());
                        item2.setUpdateTime(new Date());
                        item2.setAuditor(ShiroUtils.getUserId());
                        item2.setState("未上架");
                        assembleMapper.update(item2);

                        //修改采购入库单状态
                    } else {
                        item2.setEffectStock(item.getEffectStock());
                        item2.setUpdateTime(null);
                        item2.setAuditor(null);
                        assembleMapper.update(item2);
                    }

                }
            }

        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    public void getPutawayData(List<ProductAssemble> productAssemble) {
        Putaway putaway = new Putaway();
        Map<String, Object> params2 = new HashMap<>();

        try {
            params2.put("moduleTable", "TCC_PUTAWAY");
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号

            PurchasePlan purchasePlan = purchasePlanMapper.findByBID(productAssemble.get(0).getPlanID());//获取采购计划
            ProductActive productActive = productActiveMapper.findProductActiveByCode(productAssemble.get(0).getProductID());//获取商品母件

            putaway.setNid(moduleNidAndBid.getNid());//
            putaway.setBid(moduleNidAndBid.getBid());
            putaway.setGuid(RandomValueUtils.getGUID());
            putaway.setCreateTime(new Date());
            putaway.setProductName(productActive.getName());//商品名称
            putaway.setProductID(productActive.getCode());//商品编号
            putaway.setSonProductID(productActive.getCode());//子商品编码
            putaway.setSonProductName(productActive.getName());//子商品名称
            putaway.setfNSKU(productActive.getvFNSKU());//FNSKU
            putaway.setPlanID(purchasePlan != null ?purchasePlan.getBid():productAssemble.get(0).getPlanID());//采购计划单号
            putaway.setActualNum(productAssemble.get(0).getActualNum());//实际组装数量
            putaway.setAssembleID(productAssemble.get(0).getBid());//组装单号
            putaway.setNum(productAssemble.get(0).getActualNum());//上架数量
            putaway.setStorageID(productAssemble.get(0).getSonStorageID());//采购入库单号
            putaway.setRkBid(productAssemble.get(0).getRkBid());
            putaway.setRkGuid(productAssemble.get(0).getRkGuid());
            putaway.setbUser(ShiroUtils.getUserId());//

            putaway.setvGsBm(purchasePlan != null ?purchasePlan.getvGsBm():productAssemble.get(0).getvGsBm());//
            putaway.setvGsMc(purchasePlan != null ?purchasePlan.getvGsMc():productAssemble.get(0).getvGsMc());//

            putaway.setvHw(productAssemble.get(0).getvHw());//库区
            putaway.setvKq(productAssemble.get(0).getvKq());//货位
            putaway.setgDepot(productAssemble.get(0).getgDepot());//所在仓库

            putawayMapper.insert(putaway);//生成母件数据

//            //库存处理 将母件的库存冻结
//            StockControl newStock = new StockControl();//库存数据处理
//            Map<String, Object> paramsStock = new HashMap<String, Object>();
//            paramsStock.put("rkGuid", productAssemble.get(0).getGuid());
//            paramsStock.put("vGsBm", productAssemble.get(0).getvGsBm());
//            paramsStock.put("vHw", productAssemble.get(0).getvHw());
//            paramsStock.put("vKq", productAssemble.get(0).getvKq());
//            paramsStock.put("gDepot", productAssemble.get(0).getgDepot());
//            paramsStock.put("productcode", productAssemble.get(0).getSonCode());
//            newStock = stockControlMapper.findByMultiparameter(paramsStock);
//            newStock.setProductNum(0);
//            stockControlMapper.update(newStock);

            if (!productAssemble.get(0).getPlanID().contains("SGZZ")){//判断是否手工组装单生成
                for (ProductAssemble item : productAssemble
                ) {
                    if (item.getSonActualBalance() > 0) {
                        putaway = new Putaway();
                        putaway.setNid(moduleNidAndBid.getNid());
                        putaway.setBid(moduleNidAndBid.getBid());
                        putaway.setGuid(RandomValueUtils.getGUID());
                        putaway.setCreateTime(new Date());
                        putaway.setProductName(item.getProductName());//商品名称
                        putaway.setProductID(item.getProductID());//商品编号
                        putaway.setSonProductID(item.getSonProductID());//子商品编码
                        putaway.setSonProductName(item.getSonProductName());//子商品名称
                        putaway.setfNSKU(productActive.getvFNSKU());//FNSKU
                        putaway.setPlanID(item.getPlanID());//采购计划单号

                        putaway.setActualNum(item.getSonActualBalance());//实际组装数量
                        putaway.setAssembleID(item.getBid());//组装单号
                        putaway.setNum(item.getSonActualBalance());//上架数量
                        putaway.setStorageID(item.getSonStorageID());//采购入库单号
                        putaway.setRkGuid(item.getRkGuid());
                        putaway.setRkBid(item.getRkBid());
                        putaway.setbUser(ShiroUtils.getUserId());
                        putaway.setvGsBm(purchasePlan != null ?purchasePlan.getvGsBm():productAssemble.get(0).getvGsBm());
                        putaway.setvGsMc(purchasePlan != null ?purchasePlan.getvGsMc():productAssemble.get(0).getvGsMc());

                        putaway.setvHw(item.getvHw());//库区
                        putaway.setvKq(item.getvKq());//货位
                        putaway.setgDepot(item.getgDepot());//所在仓库
                        putawayMapper.insert(putaway);//生成子件数据
                    }

                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void getPurchasingErrorData(List<ProductAssemble> productAssemble) {
        PurchasingError purchasingError = new PurchasingError();
        Map<String, Object> params2 = new HashMap<>();

        try {
            params2.put("moduleTable", "TCC_PURCHASINGERROR");
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号

            PurchasePlan purchasePlan = purchasePlanMapper.findByBID(productAssemble.get(0).getPlanID());//获取采购计划
            ProductActive productActive = productActiveMapper.findProductActiveByCode(productAssemble.get(0).getProductID());//获取商品母件
//            List<PurchaseOrder> purchaseOrder = purchaseOrderMapper.findByPlanID(productAssemble.get(0).getPlanID());//获取采购订单
            PurchaseOrder purchaseOrder = purchaseOrderMapper.findByBID(productAssemble.get(0).getSonOrderID());//获取采购订单

            OtherCost otherCost = otherCostMapper.getTop1();//获取费用信息
            for (ProductAssemble item : productAssemble
            ) {

                if (item.getSonActualBalance() > 0 && item.getSonActualBalance() * item.getsPrice() > otherCost.getErrorCost()) {
                    purchasingError.setNid(moduleNidAndBid.getNid());
                    purchasingError.setBid(moduleNidAndBid.getBid());
                    purchasingError.setGuid(RandomValueUtils.getGUID());
                    purchasingError.setCreateTime(new Date());
                    purchasingError.setbUser(ShiroUtils.getUserId());
                    purchasingError.setvGsBm(purchasePlan.getvGsBm());
                    purchasingError.setvGsMc(purchasePlan.getvGsMc());

                    purchasingError.setOrderNumber(purchaseOrder.getAliOrderNumber());//1688订单编号
                    purchasingError.setOrderID(item.getSonOrderID());//采购订单号
                    purchasingError.setPutawayID(item.getBid());//质检上架单
                    purchasingError.setProductName(item.getBid());//商品名称
                    purchasingError.setProductID(item.getBid());//商品编号
                    purchasingError.setSonCode(item.getBid());//子件编码
                    purchasingError.setSonName(item.getBid());//子件名称
                    purchasingError.setSonPurchaseNum(item.getSonNum());//子件采购总数
                    purchasingError.setSonPrice(item.getsPrice());//子件单价
                    purchasingError.setSonStoresNum(item.getSonUseTotal());//子件上架数量

                    purchasingError.setErrorSum(item.getSonActualBalance() * otherCost.getErrorCost());//误差总金额

                    purchasingError.setErrorExplain("");//报错说明
                    purchasingError.setDispose("");//处理方式
                    purchasingError.setDisposeExplain("");//处理说明
                    purchasingError.setClaimsSum(0.00);//赔偿金额
                    purchasingError.setSalesReturnSum(0.00);//退货金额
                    purchasingError.setLogisticsChannel1("");//补发物流渠道
                    purchasingError.setLogisticsID1("");//补发物流单号

                    purchasingError.setErrorSum(item.getsPrice() * (item.getSonNum() - item.getSonActualBalance()));//误差金额

                    purchasingError.setState("未处理");//单据状态
                    purchasingErrorMapper.insert(purchasingError);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * @Description: 导入
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-08 9:15
     */
    @Override
    public AjaxResult saveImportData(Map<String, Object> params) {

        List<ProductAssemble> productAssembleList = JSON.parseArray(params.get("infoItems").toString(), ProductAssemble.class);
        if (productAssembleList == null || productAssembleList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        int x = 0;
        for (ProductAssemble item : productAssembleList) {

            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("bid", item.getBid());
            params2.put("sonCode", item.getSonCode());
            List<ProductAssemble> productAssembles = assembleMapper.findByBID(params2);

            if (productAssembles.size() > 0) {
                for (ProductAssemble item2 : productAssembles
                ) {
                    item2.setEffectStock(true);
                    item2.setAuditor(ShiroUtils.getUserId());
                    item2.setUpdateTime(new Date());
                    item2.setState("未上架");
                    item2.setSonActualBalance(item.getSonActualBalance());
                    item2.setActualNum(item.getActualNum());
                    assembleMapper.update(item2);
                }
            }
            x++;
        }
        return AjaxResult.success(x + "条数据导入成功");
    }
}